package ref;

import java.sql.Connection;
import java.sql.DriverManager;

import util.DateGroup;

public class OracleConn {
	private String htmlPath;
	private Connection oracleConn;
	private IAnalysisHandle handle = null;
	private String oracleUrl;
	private String oracleUsername;
	private String oraclePassword;
	public static void log(String msg) {
		System.out.println("[" + DateGroup.getNow() + "] " + msg);
	}
	
	public OracleConn(String htmlPath, String oracleUrl,
			String oracleUsername, String oraclePassword) {
		super();
		this.htmlPath = htmlPath;
		this.oracleUrl = oracleUrl;
		this.oracleUsername = oracleUsername;
		this.oraclePassword = oraclePassword;
	}
	public void setHandle(IAnalysisHandle handle) {
		this.handle = handle;
	}

	private void initConnection(){
		if(oracleConn==null)
			connectionOracle();
	}
	public void connectionOracle(){
		try {
			//register
			Class.forName("oracle.jdbc.OracleDriver");

			//connection
			oracleConn = DriverManager.getConnection(oracleUrl, oracleUsername, oraclePassword);
		} catch (Exception e) {
			log(" Fail to connect! " + e);
			e.printStackTrace();
		}
	}
	
	public void startTransfer() {
		if(handle != null) {
			initConnection();
			long st = System.currentTimeMillis();
			if(handle.checkTargetTable(oracleConn)) {
				try {
					handle.handleTransfer(htmlPath, oracleConn);
					log("the table ��" + handle.getTargetTable() + "�� was inserted successfully. It spended : " + getTimeSpan(st));
				} catch(Exception e) {
					e.printStackTrace(System.err);
					log("the table ��" + handle.getTargetTable() + "�� was inserted unsuccessfully. It spended : " + getTimeSpan(st));
				}
			} else {
				log("the table ��" + handle.getTargetTable() + "�� was not exsisted ");
			}
			destroyConnection();
		} else {
			log("Must specify the conversion processor ");
		}
	}
	
	private void destroyConnection() {
		try {
			if(oracleConn != null) {
				oracleConn.close();
			}
		} catch(Exception e) {
			e.printStackTrace(System.err);
		}
	}
	
	private String getTimeSpan(long startTime) {
		long span = System.currentTimeMillis() - startTime;
		if(span > 3000) {
			return "��" + ((System.currentTimeMillis() - startTime) / 1000) + "��  seconds.";
		} else {
			return "��" + (System.currentTimeMillis() - startTime) + "��	millisecond. ";
		}
	}
}